/**前后台交互工具类*/
(function ($) {
    jQuery.support.cors = true;
	/*定义全局ajax处理*/
    var index = 0;
    var stopLoadAlert = false;
    $(document).ajaxStart(function(){
        if(!stopLoadAlert)
            index = $.QuickAlert.alertLoading();
    });
    $(document).ajaxSuccess(function(event,xhr,options){
        parent.layer.close(index);
    });
    $(document).ajaxError(function(event,xhr,options,exc){
        //console.log(event);
        //console.log(xhr.static);
       var arr,reg=new RegExp("(^| )AUTH_KEY_JKCS=([^;]*)(;|$)");
        if((!document.cookie || (document.cookie && !document.cookie.match(reg))) && StoreCache.getCache("jkcsUserType")!='none'){
       
            loginLose();
            return false;
        }else{
            StoreCache.removeCache("afterLoginUrl");
        }
        parent.layer.close(index);
        var msg = "";
        var errorJson = xhr["responseJSON"];
        if(errorJson != null){
            errCode = "ERR-999999";
            errInfo = "网络超时";
            if(!StringUtils.isEmpty(errorJson["errCode"])){
                errCode = errorJson["errCode"];
                errInfo = errorJson["errInfo"];
            }
            msg = errCode + ":" + errInfo;
        }
        $.QuickAlert.alertFail({content: "抱歉，服务异常！！！<br>"+msg});
    });
    function loginLose(type){
         $.QuickAlert.alertConfirm({
                content: "登录超时，请重新登录", btn: [ "确定"], callback: function () {
                    if(ServiceType=='mobile'){
                        JSBridge.prototype.callHandler("forward",{
                                "type": "Native",
                                "toPage": "login",
                                "hasNavigation": "false",
                            });

                        }else{
                            if(type=="gzd"){
                                $.QuickUrlUtils.redirectJSBridge({url:"/html/gzd/auth/login.html"})
                            }else if(type=="ysd"){
                                $.QuickUrlUtils.redirectJSBridge({url:"/html/ysd/login/login.html"})
                            }else{
                                StoreCache.setCache("afterLoginUrl",location.href);
                                if(StoreCache.getCache("jkcsUserType")=='doctor'){
                                    $.QuickUrlUtils.redirectJSBridge({url:"/html/ysd/login/login.html"})
                                }else if(StoreCache.getCache("jkcsUserType")=='people'){
                                     $.QuickUrlUtils.redirectJSBridge({url:"/html/gzd/auth/login.html"})
                                }
                            }
                            
                           
                        }
                }
            });
    }
    function errorback(result){
        $.QuickAlert.alertFail({
            content: result['message']
        })
    }
    function exceptionback(result){
        $.QuickAlert.alertFail({
            content: result['message']
        })
    }

    $.QuickRemote = {
        code:{
            SUCCESS: "SUCCESS"
            ,ERROR: "ERROR"
            ,EXCEPTION: "EXCEPTION"
        }
        ,handler: {
            SUCCESS: function(ops){
                var result = ops['result'];
                var additionParams = ops['config']['additionParams'];
                var callback = ops['config']['callback'];
                if (additionParams != null) {
                    callback.apply(this, [result['data'], additionParams ]);
                } else {
                    callback.apply(this, [result['data']]);
                }
            }
            ,ERROR: function(ops){
                var result = ops['result'];
                if(result.code=="ERROR-AUTH-UNLOGIN_AUTH_KEY_JKCS"){
                    loginLose("gzd")
                }else if(result.code=="ERROR-AUTH-UNLOGIN_AUTH_KEY_JKCS_YSD"){
                    loginLose("ysd")
                }else{
                    var config = ops['config'];
                    var errorback = config['errorback'];
                    errorback.apply(this, [result]);
                }
                
            }
            ,EXCEPTION: function(ops){
                var result = ops['result'];
                var config = ops['config'];
                var exceptionback = config['exceptionback'];
                exceptionback.apply(this, [result]);
            }
        }
        /**ajax json交互默认配置*/
        ,def_cfg_AjaxJson: {
            funcName: ""
            //code SUCCESS
            ,callback: null
            //code ERROR
            ,errorback: errorback
            //code EXCEPTION
            ,exceptionback: exceptionback
            ,params: {}
            ,additionParams: null
        }
        /**
         * json格式的ajax交互
         * @param funcName	调用函数名
         * @param callBack	回调本地函数
         * @param params	参数
         * @param additionParams	需要回传的参数
         */
        ,AjaxJson: function(funcName, callback, params, additionParams,stopLoad)
        {
            var config = null;
            if(stopLoad) stopLoadAlert = true;
            /*强烈推荐使用配置的方式*/
            if($.isPlainObject(funcName)){
                config = $.extend({}, $.QuickRemote.def_cfg_AjaxJson, funcName);
            }else{
                config = {
                    funcName: funcName
                    ,callback: callback
                    ,params: params
                    ,errorback: errorback
                    ,exceptionback: exceptionback
                    ,additionParams: additionParams
                }
            }
            var paramsFinal = config["params"];
            if (paramsFinal == null) {
                paramsFinal = {};
            }
            for ( var key in paramsFinal) {
                var value = paramsFinal[key];
                paramsFinal[key] = encodeURI(value);
            }
            config["funcName"] = config["funcName"] + ".service";
            $.ajax({
                type : "POST",// 使用get方法访问后台
                dataType : "json",// 返回json格式的数据
                url : config["funcName"],// 要访问的后台地址
                data : paramsFinal,// 要发送的数据
                success : function(result) {
                    try{
                        var code = result['code'];
                        if(code == $.QuickRemote.code.SUCCESS){
                            $.QuickRemote.handler.SUCCESS.apply(this, [{
                                config: config
                                ,result: result
                            }]);
                        }else if(code.indexOf($.QuickRemote.code.ERROR) == 0){
                            $.QuickRemote.handler.ERROR.apply(this, [{
                                config: config
                                ,result: result
                            }]);
                        }else if(code.indexOf($.QuickRemote.code.EXCEPTION) == 0){
                            $.QuickRemote.handler.EXCEPTION.apply(this, [{
                                config: config
                                ,result: result
                            }]);
                        }
                    }catch (err){
                        if(!$.QuickVersion.isIE()){
                            console.log(err);
                        }
                    }
                }
            });
        }

        /**ajax form交互默认配置*/
        ,def_cfg_AjaxFiledFormSubmit: {
            formId: ""
            ,params: {}
            ,additionParams: null
            ,resetForm: false
            //code SUCCESS
            ,callback: null
            //code ERROR
            ,errorback: errorback
            //code EXCEPTION
            ,exceptionback: exceptionback
        }
        /**
         * ajax表单提交
         */
        ,AjaxFiledFormSubmit : function(formId, callback, params, additionParams, resetForm)
        {
            var config = null;
            if($.isPlainObject(formId)){
                config = $.extend({}, $.QuickRemote.def_cfg_AjaxFiledFormSubmit, formId);
            }else{
                if(!resetForm)
                {
                    resetForm = false;
                }
                config = {
                    formId: formId
                    ,callback: callback
                    ,params: params
                    ,additionParams: additionParams
                    ,resetForm: resetForm
                }
            }
            var paramsFinal = config["params"];
            if (paramsFinal == null) {
                paramsFinal = {};
            }
            for ( var key in paramsFinal) {
                var value = paramsFinal[key];
                paramsFinal[key] = encodeURI(value);
            }

            var options = {
                type:'post',
                dataType:'json',
                data: config["params"],
                resetForm: config["resetForm"],
                success:function(result){
                    try{
                        var code = result['code'];
                        if(code == $.QuickRemote.code.SUCCESS){
                            $.QuickRemote.handler.SUCCESS.apply(this, [{
                                config: config
                                ,result: result
                            }]);
                        }else if(code.indexOf($.QuickRemote.code.ERROR) == 0){
                            $.QuickRemote.handler.ERROR.apply(this, [{
                                config: config
                                ,result: result
                            }]);
                        }else if(code.indexOf($.QuickRemote.code.EXCEPTION) == 0){
                            $.QuickRemote.handler.EXCEPTION.apply(this, [{
                                config: config
                                ,result: result
                            }]);
                        }
                    }catch (err){
                        if(!$.QuickVersion.isIE()){
                            console.log(err);
                        }
                    }
                }
            };
            var cfg_formId = config["formId"];
            var action = $("#" + cfg_formId).attr("action");
            if(action.slice(-".service".length) != ".service"){
                action = action + ".service"
            }
            $("#" + cfg_formId).attr("action", action);
            $("#" + cfg_formId).ajaxSubmit(options);
        }
        ,/**
         * XML格式的ajax交互
         * @param funcName	调用函数名
         * @param callBack	回调本地函数
         * @param params	参数
         * @param additionParams	需要回传的参数
         */
        AjaxXML: function(funcName, callBack, params, additionParams)
        {
            if (params == null) {
                params = {};
            }
            for ( var key in params) {
                var value = params[key];
                params[key] = encodeURI(value);
            }
            var index;
            $.ajax({
                type : "POST",// 使用get方法访问后台
                dataType : "XML",// 返回XML格式的数据
                url : funcName+".service",// 要访问的后台地址
                data : params,// 要发送的数据
                beforeSend : function() {// 发送请求前调用函数
                    index = $.QuickAlert.alertLoading();
                },
                complete : function() {// 发送请求后调用参数，不管成功失败都会调用
                    parent.layer.close(index);
                },
                success : function(result) {
                    try{
                        callBack = eval(callBack);
                        if (additionParams != null) {
                            callBack.apply(this, [ result, additionParams ]);
                        } else {
                            callBack.apply(this, [ result ]);
                        }
                    }catch (err){
                        if(!$.QuickVersion.isIE()){
                            console.log(err);
                        }
                    }
                },
                error : function(re) {// 发生错误时调用。
                    $.QuickAlert.alertFail({content: re.responseText});
                }
            });
        }
        ,/**
         * HTML格式的ajax交互
         * @param funcName	调用函数名
         * @param callBack	回调本地函数
         * @param params	参数
         * @param additionParams	需要回传的参数
         */
        AjaxHTML: function(funcName, callBack, params, additionParams)
        {
            if (params == null) {
                params = {};
            }
            for ( var key in params) {
                var value = params[key];
                params[key] = encodeURI(value);
            }
            var index;
            $.ajax({
                type : "POST",// 使用get方法访问后台
                dataType : "HTML",// 返回XML格式的数据
                url : funcName,// 要访问的后台地址
                data : params,// 要发送的数据
                beforeSend : function() {// 发送请求前调用函数
                    index = $.QuickAlert.alertLoading();
                },
                complete : function() {// 发送请求后调用参数，不管成功失败都会调用
                    parent.layer.close(index);
                },
                success : function(result) {
                    try{
                        callBack = eval(callBack);
                        if (additionParams != null) {
                            callBack.apply(this, [ result, additionParams ]);
                        } else {
                            callBack.apply(this, [ result ]);
                        }
                    }catch (err){
                        if(!$.QuickVersion.isIE()){
                            console.log(err);
                        }
                    }
                },
                error : function(re) {// 发生错误时调用。
                    $.QuickAlert.alertFail({content: re.responseText});
                }
            });
        }
        /**
         * json格式的ajax交互 异步调用
         * @param funcName	调用函数名
         * @param callBack	回调本地函数
         * @param params	参数
         * @param additionParams	需要回传的参数
         */
        ,AjaxJsonAsync: function(funcName, callBack, params, additionParams)
        {
            if (params == null) {
                params = {};
            }
            for ( var key in params) {
                var value = params[key];
                params[key] = encodeURI(value);
            }
            var index;
            $.ajax({
                async: false,
                type : "POST",// 使用get方法访问后台
                dataType : "json",// 返回json格式的数据
                url : funcName+".service",// 要访问的后台地址
                data : params,// 要发送的数据
                beforeSend : function() {// 发送请求前调用函数
                    index = $.QuickAlert.alertLoading();
                },
                complete : function() {// 发送请求后调用参数，不管成功失败都会调用
                    parent.layer.close(index);
                },
                success : function(result) {
                    try{
                        callBack = eval(callBack);
                        if (additionParams != null) {
                            callBack.apply(this, [ result, additionParams ]);
                        } else {
                            callBack.apply(this, [ result ]);
                        }
                    }catch (err){
                        if(!$.QuickVersion.isIE()){
                            console.log(err);
                        }
                    }
                },
                error : function(re) {// 反生错误时调用。
                    $.QuickAlert.alertFail({content: re.responseText});
                }
            });
        }
        ,formSubmit: function(formId, params)
        {
            if(params)
            {
                $.each(params, function(key, value){
                    var input = $("<input>");
                    input.attr("name", key);
                    input.attr("value", value);
                    input.appendTo($("#"+formId));
                })
            }
            $("#"+formId).submit();
        }
        ,AjaxFiledFormSubmitJsonp : function(formId, callBack, params, additionParams, resetForm)
        {
            if(params == null){
                params = {};
            }
            for(var key in params)
            {
                var value = params[key];
                params[key] = encodeURI(value);
            }
            if(!resetForm)
            {
                resetForm = false;
            }
            var index ;
            var options = {
                type:'get',
                dataType:'jsonp',
                jsonp: "callback",
                data:params,
                resetForm: resetForm,
                beforeSend : function() {// 发送请求前调用函数
					/*index = parent.layer.load(2, {
					 shade : [ 0.3, '#fff' ]
					 }); // 0.1透明度的白色背景*/
                    index = $.QuickAlert.alertLoading();
                },
                complete : function() {// 发送请求后调用参数，不管成功失败都会调用
                    parent.layer.close(index);
                },
                success:function(result){
//		    			parent.layer.closeAll();
                    callBack = eval(callBack);
                    if(additionParams)
                    {
                        callBack.apply(this, [result, additionParams]);
                    }
                    else
                    {
                        callBack.apply(this, [result]);
                    }
                },
                error: function(re){//错误时调用。
                    $.QuickAlert.alertFail({content: re.responseText});
                }
            };
            $("#" + formId).ajaxSubmit(options);
        }
    };
})(jQuery);










